package com.sky.db.meta;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;


/**
 * 操作JDBC的工具类
 *
 * @return
 * @throws Exception
 */
public class JdbcHelper {

    public Connection connection = null;

    public JdbcHelper() throws Exception {
        connection = getConnection();
    }

    public JdbcHelper(String jdbcUrl, String user, String password) throws Exception {
        connection = getConnection(jdbcUrl, user, password);
    }

    public static void main(String args[]) {
        try {
            Connection conn = new JdbcHelper().connection;
            System.out.println(conn);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void update(String sql, Object... args) {
        PreparedStatement preparedStatement = null;
        try {
            preparedStatement = connection.prepareStatement(sql);

            for (int i = 0; i < args.length; i++) {
                preparedStatement.setObject(i + 1, args[i]);

            }
            preparedStatement.execute();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JdbcHelper.releaseDB(null, preparedStatement, connection);
        }

    }

    public <T> T getEntity(Class<T> clazz, String sql, Object... args) {

        T entity = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;

        try {
            preparedStatement = connection.prepareStatement(sql);


            for (int i = 0; i < args.length; i++) {
                preparedStatement.setObject(i + 1, args[i]);

            }
            resultSet = preparedStatement.executeQuery();

            Map<String, Object> map = new HashMap<String, Object>();

            ResultSetMetaData rsmd = resultSet.getMetaData();

            if (resultSet.next()) {
                for (int i = 0; i < rsmd.getColumnCount(); i++) {
                    String columnLabel = rsmd.getColumnLabel(i + 1);
                    Object columnValue = resultSet.getObject(columnLabel);
                    map.put(columnLabel, columnValue);
                }
            }
            System.out.print(map);

            if (map.size() > 0) {
                entity = clazz.newInstance();
                EntryMapSet(clazz, entity, map);
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JdbcHelper.releaseDB(resultSet, preparedStatement, connection);
        }
        return entity;
    }


    public <T> List<T> getForList(Class<T> clazz, String sql, Object... args) {
        List<T> list = new ArrayList<T>();

        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;

        try {
            preparedStatement = connection.prepareStatement(sql);


            for (int i = 0; i < args.length; i++) {
                preparedStatement.setObject(i + 1, args[i]);
            }
            resultSet = preparedStatement.executeQuery();

            List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>();


            ResultSetMetaData rsmd = resultSet.getMetaData();

            while (resultSet.next()) {
                Map<String, Object> map = new HashMap<String, Object>();
                for (int i = 0; i < rsmd.getColumnCount(); i++) {
                    String columnLabel = rsmd.getColumnLabel(i + 1);
                    Object columnValue = resultSet.getObject(columnLabel);
                    map.put(columnLabel, columnValue);
                }
                mapList.add(map);
            }
            System.out.print(mapList);

            if (mapList.size() > 0) {

                for (Map<String, Object> map : mapList) {
                    T entity = clazz.newInstance();
                    EntryMapSet(clazz, entity, map);
                    list.add(entity);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JdbcHelper.releaseDB(resultSet, preparedStatement, connection);
        }
        return list;
    }

    /**
     * 关闭释放数据库
     *
     * @param statement
     * @param connection
     */
    public static void releaseDB(ResultSet resultSet, Statement statement, Connection connection) {
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }


    }


    public Connection getConnection() throws Exception {

        String driverClass = null;
        String jdbcUrl = null;
        String user = null;
        String password = null;

        Properties properties = new Properties();

        //InputStream in = Thread.currentThread().getContextClassLoader().getSystemResourceAsStream("application.properties");

        InputStream in =this.getClass().getClassLoader().getResourceAsStream("application.properties");
        properties.load(in);
        driverClass =
                properties.getProperty("spring.datasource.driverClassName");
        jdbcUrl = properties.getProperty("spring.datasource.url");
        user = properties.getProperty("spring.datasource.user");
        password = properties.getProperty("spring.datasource.password");
        Class.forName(driverClass);

        Properties info = new Properties();
        info.put("user", user);
        info.put("password", password);
        Connection connection = DriverManager.getConnection(jdbcUrl, user, password);
        return connection;

    }

    public Connection getConnection(String jdbcUrl, String user, String password) throws Exception {

        String driverClass = "com.mysql.jdbc.Driver";
        Class.forName(driverClass);

        Properties info = new Properties();
        info.put("user", user);
        info.put("password", password);
        Connection connection = DriverManager.getConnection(jdbcUrl, user, password);
        return connection;

    }

    private <T> void EntryMapSet(Class<T> clazz, T entity, Map<String, Object> map) throws NoSuchFieldException, NoSuchMethodException, IllegalAccessException, InvocationTargetException {
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            String fieldName = entry.getKey();
            Object value = entry.getValue();
            Field field = clazz.getDeclaredField(fieldName);

            Method m = entity.getClass().getDeclaredMethod(setMethod(field.getName()), field.getType());
            m.invoke(entity, value);
        }
    }

    private static String setMethod(String name) {
        return "set" + name.substring(0, 1).toUpperCase() + name.substring(1);
    }
}
